import paho.mqtt.client as mqtt
import time
import json
from threading import Event 

class MQTTPublisher:
    def __init__(self,broker="47.93.172.78",port=1883,
            keepalive=60,topic="default/topic", message="Hello MQTT"):
        self.broker = broker
        self.port = port
        self.keepalive = keepalive
        self._current_topic = topic
        self._current_message = message
        self.connected_event = Event()  # 用于等待连接完成
        self.client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2,)
        self.client.on_connect = self._on_connect
        try:
            self.client.connect(self.broker, self.port, self.keepalive)
            self.client.loop_start()
            self.connected_event.wait(timeout=0.6)
            self.publish()
        except Exception as e:
            print(f"[Publisher]初始化错误:{e}")
        finally:
            self. client.disconnect()
            self.client.loop_stop()


    def _on_connect(self, client, userdata, flags, rc,properties=None):
        if rc == 0:
            print(f"Publisher connected to {self.broker}:{self.port} with code {rc}")
        else:
             print(f"[Publisher] Connection failed: {rc}")
    
    def publish(self):
         """暴露的接口：动态发布消息到指定主题"""
         result = self.client.publish(self._current_topic,self._current_message)
         if result[0] == mqtt.MQTT_ERR_SUCCESS:
             print(f"Published to `{self._current_topic}`: {self._current_message}")
         else:
             print(f"Failed to publish to `{topic}`")

if __name__=="__main__":
    # 模拟后端发送的绑定消息
    bind_payload = {
        "command":"upload",
        "data":{
            "device_id": "DEV-123456",  # 目标设备ID
            "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsidXNlcmlkIjoxLCJ1c2VybmFtZSI6InpoYW5nc2FuIn0sImV4cCI6MTc0MzEwMjQwOH0.wY7y3p6-qhjALODkO23mYXwQEUZ1Q_oW9U8oNQSJi1Y",  # 用户令牌
        }
    }

    device_id="DEV-123456"

    publisher=MQTTPublisher(topic=f"device/{device_id}/commands",message=json.dumps(bind_payload))
